package com.example.administrator.text;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import adapter.VPWeAccount;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.AgentIp;
import util.BReceiverUtil.AlarmReceiver;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.RetunDialog;
import view.diaLogView.UploadDialog;

import static data.SharedPreferencesUtils.getParam;

/**
 * 上网预约
 */
public class AppointTimeActivity extends BaseActivity {
     public static String mRenew = "renew";
     public static String mbreakNetWorkstate = "breakNetWorkstate";
     public static String mNetWorkstate = "NetWorkstate";
     public static String mShow_TV_NetWorkstate= "Show_TV_NetWorkstate";
     public static String mPackage_NetWorkstate = "Package_NetWorkstate";
     public static String  SSID_PC_NetWorkstate = "SSID_PC_NetWorkstate";  //双ssid 手机授权联网
     private String mId,mToken,mType;
     private String mSessionid = "";
     private int mTime = 6;
     private UploadDialog mUploadDialog;
     private FrameLayout mFrameLayout;
     private TextView mTV;
     private ArrayList<String> mList = new ArrayList<>();
     private ArrayList<Integer> mList1 = new ArrayList<>();

    @Bind(R.id.activity_appointtime_list)   ListView mListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appointtime);
        mFrameLayout = (FrameLayout)findViewById(R.id.appointtime_frame);
        mTV = (TextView)findViewById(R.id.activity_appointtime_tv);
        ButterKnife.bind(this);
        HomeUtil.getHemeUtilNew().getStatusBar(this, mFrameLayout);
        init();
    }

    private void init() {
        EventBus.getDefault().register(this);
        mId = (String) SharedPreferencesUtils.getParam(AppointTimeActivity.this, HomeUtil.mUseridDB, "");
        mToken = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mTokenDB, "");
        mType = getIntent().getStringExtra("type");

        if(mType.equals(mNetWorkstate)){
            mTV.setText("请选择上网时长");
        }else if(mType.equals(mRenew)){
            mTV.setText("请选择续时时长");
        }else if(mType.equals(SSID_PC_NetWorkstate)){
            mTV.setText("请选择授权时长");
            mSessionid = getIntent().getStringExtra("sessionid");
        }
        getData();

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtil.eE("position","........parent........"+position);
                mTime = mList1.get(position)*60;
                isAlive();
            }
        });

    }

    private void getData(){
        mUploadDialog = new UploadDialog(this,"加载中");
        mUploadDialog.show();
        mMap.put("siteAreaid",MyApplication.getApp().getSiteAreaid());
        mMap.put("pattern",MyApplication.getApp().getmPattern());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        final long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.getUrlNew().url_planNetSchedule,stringJson,mToken,mId,time);
        final Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mId,Url.getUrlNew().url_planNetSchedule,stirngSign,time);
        getLogger().info("选择时长列表请求-->"+"fwq--"+MyApplication.getApp().getFWQString()+"--type--"+"time"+StringUtil.getStringUtilNew().getTimeInstance()+"...NF_callid..."+map.get("NF_callid")+"..stringJson..."+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(this,MyApplication.getApp().getFWQString(),8000,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    getLogger().info("选择时长列表请求结果-->"+"response--"+response);
                    mUploadDialog.dismiss();
                    JSONObject jsonObject = new JSONObject(response);
                    if(jsonObject.getInt("code") == 1){
                        JSONArray jsonArray = jsonObject.optJSONArray("schedule");
                        setList(getListData(1,jsonArray));
                    }else {
                        setList(getListData(1,null));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    setList(getListData(1,null));
                }
            }

            @Override public void onFailure(Throwable error) {
                setList(getListData(1,null));
                mUploadDialog.dismiss();
                getLogger().info("getJudgeIP--->onFailure--->"+"time"+StringUtil.getStringUtilNew().getTimeInstance()+error);
            }
        });
    }

    private void setList(ArrayList list){
        LogUtil.eE("","......setList.....开始设置...");
        VPWeAccount adapter = new VPWeAccount(this,list);
        mListView.setAdapter(adapter);
        mListView.setDividerHeight(0);
    }

    private ArrayList<String> getListData(int type, JSONArray jsonArray) {
        if(type == 1 ){
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    JSONObject jsonobject = jsonArray.getJSONObject(i);
                    mList.add(jsonobject.getInt("planTime")+"小时");
                    mList1.add(jsonobject.getInt("planTime"));
                } catch (JSONException e) {
                    e.printStackTrace();
                    mList.add("1小时");
                    mList1.add(1);
                }
            }
        }else {
           mList.add("1小时");
           mList.add("2小时");
           mList1.add(1);
           mList1.add(2);
        }
        return mList;
    }

    @OnClick(R.id.image_appointtime)
    void getFinish(){
        finish();
    }

    /*** 订阅事件FirstEvent*/
    @Subscribe
    public void onEventMainThread(final String string) throws JSONException {
        if(string !=null && string.equals("appintTime_ok")){
            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                @Override public void run() {
                    finish();
                }
            },2000);
        }
    }

    private void ok(){
        mUploadDialog.getStringShow("联网中");
        HashMap<String, Object> map = new HashMap<>();
        map.put("ip", getInformation.getNewGetInformation(this).getI_IP());
        map.put("userid",mId);
        map.put("mac",getInformation.getNewGetInformation(this).getIMAC());
        map.put("planTime",mTime);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        final long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngNetwork_planNet,stringJson,mToken,mId,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mId,Url.mStirngNetwork_planNet,stirngSign,time);
        String fwq = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");
        getLogger().info("时长联网-ok-"+fwq+"mTime:"+mTime+"stirngSign"+stirngSign+"...stringJson..."+stringJson+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,fwq,1,map1,new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    getLogger().info("时长联网-ok-response()--->String--"+response);
                    final JSONObject json = new JSONObject(response);
                    if(json.getInt("code") == 1){
                             if(json.getInt("connect") == 1){
                                 mUploadDialog.getStringShow("验证中");
                                 AgentIp.newInstance(AppointTimeActivity.this).setNetWorkstate2(new AgentIp.OnNetworkStateClickListener() {
                                     @Override
                                     public void onClick(boolean state) {
                                         mUploadDialog.dismiss();
                                          if(state){
                                              final RetunDialog retunDialog = new RetunDialog(AppointTimeActivity.this,"",3,true);
                                              retunDialog.show();
                                              HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                                  @Override public void run() {
                                                      retunDialog.dismiss();
                                                      finish();
                                                  }
                                              },1000);
                                              Url.getUrlNew().setNotification(true);
                                              HomeUtil.getHemeUtilNew().setPushAurora(AppointTimeActivity.this);
                                              if(mType !=null && !mType.equals("")){
                                                      SharedPreferencesUtils.setParam(AppointTimeActivity.this,HomeUtil.mMoneyTime,StringUtil.getStringUtilNew().getTimeInstance());
                                                      SharedPreferencesUtils.setParam(AppointTimeActivity.this,HomeUtil.mNetworkingTime,mTime);
                                              }
                                              EventBus.getDefault().post("NetWorkstate_ok");
                                              if(MyApplication.getApp().getSiteAreaid() == 10003){
                                                  if(mTime == 0){
                                                   SharedPreferencesUtils.getParam(AppointTimeActivity.this,"altair",10003);
                                                  }else {SharedPreferencesUtils.getParam(AppointTimeActivity.this,"altair",3);}

                                              }else {SharedPreferencesUtils.getParam(AppointTimeActivity.this,"altair",3);}
                                              Intent intent = new Intent(AppointTimeActivity.this,AlarmReceiver.class);
                                              intent.putExtra("networking","updateNetwork66");
                                              sendBroadcast(intent);
                                          }else {
                                              Toast.makeText(AppointTimeActivity.this,"预约联网失败,假成功",Toast.LENGTH_SHORT).show();
                                          }
                                     }
                                 });
                             }else {
                                mUploadDialog.dismiss();
                                getPrompt(2,json);
                             }
                    }else if(json.getInt("code") == 2 || json.getInt("code") == 0){
                        if(json.getInt("reason") == 4){
                            getNetworking();
                        }else{
                            mUploadDialog.dismiss();
                            getPrompt(2,json);                         }
                    }else if(json.getInt("code") == -2){
                        mUploadDialog.dismiss();
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(AppointTimeActivity.this);
                        crowdRetunDialog.show();
                    }else {
                        mUploadDialog.dismiss();
                        getPrompt(2,json);                      }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mUploadDialog.dismiss();
                    Toast.makeText(AppointTimeActivity.this,"预约失败",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                getLogger().info("时长联网-ok-onFailure()--->error--"+error);
                mUploadDialog.dismiss();
                Toast.makeText(AppointTimeActivity.this,"预约失败",Toast.LENGTH_SHORT).show();
                StringUtil.getStringUtilNew().getExceptionCode(AppointTimeActivity.this,error.toString());
            }
        });
    }

    private void ok1(){
        mUploadDialog.getStringShow("联网中");
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid",mId);
        map.put("planTime",mTime);
        map.put("wayid",MyApplication.getApp().getmPattern());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        final long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.getUrlNew().network_planAdd,stringJson,mToken,mId,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mId,Url.getUrlNew().network_planAdd,stirngSign,time);
        String fwq = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");
        getLogger().info("续时联网-ok---->fwq--"+fwq+"mTime:"+mTime+"stringJson"+stringJson+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,fwq,1,map1, new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    getLogger().info("续时联网()-->response()--->String--"+response);
                    JSONObject json = new JSONObject(response);
                    if(json.getInt("code") == 1){
                            mUploadDialog.getStringShow("验证中");
                            AgentIp.newInstance(AppointTimeActivity.this).setNetWorkstate2(new AgentIp.OnNetworkStateClickListener() {
                                @Override
                                public void onClick(boolean state) {
                                    mUploadDialog.dismiss();
                                    if(state){
                                        final RetunDialog retunDialog = new RetunDialog(AppointTimeActivity.this,"",8,true);
                                        retunDialog.show();
                                        HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                            @Override public void run() {
                                                retunDialog.dismiss();
                                                finish();

                                            }
                                        },1000);
                                        Url.getUrlNew().setNotification(true);
                                        if(mType !=null && !mType.equals("")){
                                            String monryTime = (String) getParam(AppointTimeActivity.this,HomeUtil.mMoneyTime,"");  //上网的时间
                                            int time = (int) getParam(AppointTimeActivity.this,HomeUtil.mNetworkingTime,4);        //预约的时长
                                            long lon = StringUtil.getStringUtilNew().compareTime(monryTime,time);
                                            if(lon > 0){
                                                SharedPreferencesUtils.setParam(AppointTimeActivity.this,HomeUtil.mNetworkingTime,(mTime+time));
                                            }else {
                                                SharedPreferencesUtils.setParam(AppointTimeActivity.this,HomeUtil.mMoneyTime,StringUtil.getStringUtilNew().getTimeInstance());
                                                SharedPreferencesUtils.setParam(AppointTimeActivity.this,HomeUtil.mNetworkingTime,mTime);
                                            }
                                        }
                                        if(MyApplication.getApp().getSiteAreaid() == 10003){
                                            if(mTime == 0){
                                                SharedPreferencesUtils.getParam(AppointTimeActivity.this,"altair",10003);
                                            }else {SharedPreferencesUtils.getParam(AppointTimeActivity.this,"altair",3);}

                                        }else {SharedPreferencesUtils.getParam(AppointTimeActivity.this,"altair",3);}

                                    }else {
                                        Toast.makeText(AppointTimeActivity.this,"预约联网失败，假成功",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                    }else if(json.getInt("code") == 2 || json.getInt("code") == 0){
                        if(json.getInt("reason") == 4){
                            getNetworking();
                        }else{
                            mUploadDialog.dismiss();
                            getPrompt(1,json);
                        }
                    }else if (json.getInt("code") == -2) {
                        mUploadDialog.dismiss();
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(AppointTimeActivity.this);
                        crowdRetunDialog.show();
                    }else {
                        mUploadDialog.dismiss();
                        getPrompt(1,json);                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mUploadDialog.dismiss();
                    Toast.makeText(AppointTimeActivity.this,"预约失败",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                getLogger().info("续时联网-->onFailure()--->error--"+error);
                mUploadDialog.dismiss();
                Toast.makeText(AppointTimeActivity.this,"预约失败",Toast.LENGTH_SHORT).show();
                StringUtil.getStringUtilNew().getExceptionCode(AppointTimeActivity.this,error.toString());
            }
        });
    }

    /**
     * 授权pc联网
     */
    private void ssidPCNetWorkstate(){
        mUploadDialog.getStringShow("授权中");
        HashMap<String, Object> map = new HashMap<>();
        map.put("sessionid",mSessionid);
        map.put("userid",mId);
        map.put("planTime",mTime);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        final long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.getUrlNew().PCNetQr_pcQrselfNet,stringJson,mToken,mId,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mId,Url.getUrlNew().PCNetQr_pcQrselfNet,stirngSign,time);
        String fwq = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");
        getLogger().info("ssidPCNetWorkstate()-->"+"...stringJson..."+stringJson+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,fwq,1,map1, new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    getLogger().info("ssidPCNetWorkstate()--->String--"+response);
                    JSONObject json = new JSONObject(response);
                    if(json.getInt("code") == 1){
                        mUploadDialog.dismiss();
                        int connect  = json.getInt("connect");
                        if(connect == 1){
                            final RetunDialog retunDialog = new RetunDialog(AppointTimeActivity.this,"",6,true);
                            retunDialog.show();
                            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                @Override public void run() {
                                    retunDialog.dismiss();
                                    finish();
                                }
                            },1000);
                        }else {
                            getPrompt(0,json);
                        }
                    }else if (json.getInt("code") == -2) {
                        mUploadDialog.dismiss();
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(AppointTimeActivity.this);
                        crowdRetunDialog.show();
                    }else {
                        mUploadDialog.dismiss();
                        getPrompt(0,json);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mUploadDialog.dismiss();
                    Toast.makeText(AppointTimeActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                getLogger().info("ssidPCNetWorkstate()--->error--"+error);
                mUploadDialog.dismiss();
                Toast.makeText(AppointTimeActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                StringUtil.getStringUtilNew().getExceptionCode(AppointTimeActivity.this,error.toString());
            }
        });
    }

    private void isAlive(){
        mMap = new HashMap<>();
        if(mId.equals("")){
            mMap.put("userid","0");
        }else {
            mMap.put("userid",mId);
        }
        mMap.put("visitType",1);
        mMap.put("ip",getInformation.getNewGetInformation(this).getI_IP());
        mMap.put("mac",getInformation.getNewGetInformation(this).getIMAC());
        mMap.put("apMac",getInformation.getNewGetInformation(this).getWiFiMac());
        mMap.put("apName",getInformation.getNewGetInformation(this).getWIFIName());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        if(mUploadDialog == null){
            mUploadDialog = new UploadDialog(this,"连接中");
        }else {
            mUploadDialog.getStringShow("连接中");
        }
        mUploadDialog.show();
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        final Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        final String fwq = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");
        getLogger().info("isAlive()--->"+"fwq--"+fwq+"type--"+"time"+StringUtil.getStringUtilNew().getTimeInstance()+"...NF_callid..."+map.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,fwq,1500,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    getLogger().info("isAlive()--->onSuccess--->"+"String--"+response);
                    if (jsonObject.getInt("code") == 1) {
                        if (!fwq.equals(Url.getUrlNew().getAppIP())) {
                            SharedPreferencesUtils.setParam(AppointTimeActivity.this, HomeUtil.mFWQ, fwq);
                        }
                        if (jsonObject.has("siteAreaid")){
                            MyApplication.getApp().setSiteAreaid(jsonObject.getInt("siteAreaid"));
                        }
                        if(mType.equals(mNetWorkstate)){
                            ok();
                        }else if(mType.equals(mRenew)){
                            ok1();
                        }else if(mType.equals(SSID_PC_NetWorkstate)){
                            ssidPCNetWorkstate();
                        }

                    }else {
                        isAliveNo();
                    }
                } catch (JSONException e) {
                    isAliveNo();
                }
            }

            @Override public void onFailure(Throwable error) {
                isAliveNo();
            }
        });
    }


    private void isAliveNo(){
        getLogger().info("isAlive()---->onFailure--->");
        AgentIp.newInstance(AppointTimeActivity.this).getIp(new AgentIp.OnAgentIpItemClickListener() {
            @Override
            public void onItemClick(String fwq) {
                getLogger().info("seekSuccess()--->onItemClick()代理地址"+fwq);
                if(fwq.equals("没有查到")){
                    mUploadDialog.dismiss();
                    Toast.makeText(AppointTimeActivity.this,"没有找到代理服务器",Toast.LENGTH_SHORT).show();
                }else {
                    if (!fwq.equals(Url.getUrlNew().getAppIP())) {
                        SharedPreferencesUtils.setParam(AppointTimeActivity.this, HomeUtil.mFWQ, fwq);
                    }
                    if(mType.equals(mNetWorkstate)){
                        ok();
                    }else if(mType.equals(mRenew)){
                        ok1();
                    }else if(mType.equals(SSID_PC_NetWorkstate)){
                        ssidPCNetWorkstate();
                    }
                }
            }
        });
    }

    /**
     * 联网
     */
    private void getNetworking(){
        NetWorkstateUtil.getInstance().getNetworking(AppointTimeActivity.this,mUploadDialog,mRenew);
    }

    /**
     * 提示 0 授权  1：续时  2：联网
     */
    private void getPrompt(int type,JSONObject json) throws JSONException {
        switch (type){
            case 0:
                if(json.has("msg")){
                    Toast.makeText(AppointTimeActivity.this,json.getString("msg"),Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(AppointTimeActivity.this,"授权失败,可以重新扫码",Toast.LENGTH_SHORT).show();
                }
                break;
            case 1:
                if(json.has("msg")){
                    Toast.makeText(AppointTimeActivity.this,json.getString("msg"),Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(AppointTimeActivity.this,"续时失败",Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if(json.has("msg")){
                    Toast.makeText(AppointTimeActivity.this,json.getString("msg"),Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(AppointTimeActivity.this,"联网失败",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
